﻿using System;
using System.Linq;
using System.ServiceModel;
using ET.CommonLibrary.Log;
using ET.Score.Service;
using ET.Score.Service.Interfaces;

namespace ET.Score.SharedLibrary.Wcf
{
    public class HeartMonitorProvider : HeartBeatInvoker<IHeartBeatService>
    {
        private readonly string endpointName;

        public static DuplexChannelFactory<IHeartBeatService> CreateChannelFactory(string endpointName = null, IScoreCallback callbackObj = null)
        {
            if (endpointName == null)
                endpointName = typeof(HeartMonitorProvider).FullName;

            if (callbackObj == null)
                callbackObj = new ScoreCallbackObject();

            var factory = new DuplexChannelFactory<IHeartBeatService>(callbackObj, endpointName);
            return factory;
        }

        private static WcfMachineInfo reportInfo;

        public static bool HeartBeat(IHeartBeatService proxy)
        {
            try
            {
                if(reportInfo==null)
                {
                    reportInfo = GetMoachineInfo();
                }
                proxy.HeartMonitor(reportInfo);
            }
            catch(Exception EX)
            {

            }
            return true;
        }

        public HeartMonitorProvider(IScoreCallback callbackObj = null, string endpointName = null)
            : base(CreateChannelFactory(endpointName, callbackObj), HeartBeat)
        {
            this.endpointName = endpointName;
            reportInfo = GetMoachineInfo();
            EnvironmentContext.Logger.Info("心跳上报信息已读取:Id:{0}, type:{1}", reportInfo.MachineIP, reportInfo.MachineType);
        }

        private static WcfMachineInfo GetMoachineInfo()
        {
            var macList = Util.GetAllMac();

            string str = EnvironmentContext.AppSettings["MachineInfo.MachineType"];
            int machineType = int.Parse(str);

            return new WcfMachineInfo()
            {
                //MachineIP = macList.First().ToLowerInvariant(),
                MachineIP = EnvironmentContext.AppSettings["LocalIP"],
                MachineType = machineType,
                UserName = EnvironmentContext.AppSettings["UserName"]
            };
        }
    }
}

